import { Button, message, Popconfirm, Popover, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { delJobLog, queryAppJobLogList, delBatchJobLog } from './service';
import './monitor.less';

/**
 *  批量删除
 * @param selectedRows
 */

const handleDelBatch = async (selectedRows) => {
  message.loading({ content: '正在批量删除', duration: 0 });
  if (!selectedRows) return true;
  await delBatchJobLog({
    logIdList: selectedRows.map((row) => row.id),
  })
    .then((res) => {
      if (res.code === 200) {
        message.destroy();
        message.success('批量删除成功');
        return true;
      }
      message.destroy();
      message.error('批量删除失败请重试');
      return false;
    })
    .catch(() => {
      message.destroy();
      message.error('批量删除失败请重试');
      return false;
    });
  return true;
};

const TableList = () => {
  const actionRef = useRef();
  const [selectedRowsState, setSelectedRows] = useState([]);

  /**
   * 删除接口日志
   * @param fields
   */

  const handleDel = async (param) => {
    message.loading({ content: '正在删除', duration: 0 });
    await delJobLog({
      id: param.id,
    })
      .then((res) => {
        if (res.code === 200) {
          message.destroy();
          message.success('删除成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.destroy();
          message.error('删除失败请重试');
        }
      })
      .catch(() => {
        message.destroy();
        message.error('删除失败请重试');
      });
  };

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      sorter: false,
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '监控名称',
      key: 'appjobname',
      dataIndex: 'appjobname',
      sorter: true,
    },
    {
      title: '接口描述',
      key: 'descr',
      dataIndex: 'descr',
      sorter: false,
      hideInSearch: false,
    },
    {
      title: '方法参数',
      key: 'params',
      dataIndex: 'params',
      sorter: false,
      hideInSearch: true,
      width: 380,
      render: (text) => {
        return (
          <>
            <Popover
              placement="top"
              title={'方法参数'}
              content={text}
              trigger="hover"
              className={'wrongSty'}
            >
              <div className={'twoLineSty'}>{text}</div>
            </Popover>
          </>
        );
      },
    },
    {
      title: '异常信息',
      key: 'result',
      dataIndex: 'result',
      sorter: false,
      hideInSearch: true,
      width: 380,
      render: (text) => {
        return (
          <>
            <Popover
              placement="top"
              title={'异常信息'}
              content={text}
              trigger="hover"
              className={'wrongSty'}
            >
              <div className={'twoLineSty'}>{text}</div>
            </Popover>
          </>
        );
      },
    },
    {
      title: '耗时',
      key: 'restime',
      dataIndex: 'restime',
      sorter: false,
      hideInSearch: true,
      render: (text) => {
        let tag;
        let textNum;
        if (!Number.isNaN(text)) {
          textNum = parseInt(text, 10);
          if (textNum <= 500) {
            tag = (
              <Tag color="#009688" style={{ width: '60px', align: 'center' }}>
                {text}ms
              </Tag>
            );
          } else if (textNum > 500 && textNum <= 1000) {
            tag = (
              <Tag color="#1890ff" style={{ width: '60px', align: 'center' }}>
                {text}ms
              </Tag>
            );
          } else if (textNum > 1000 && textNum <= 2000) {
            tag = (
              <Tag color="#FFB800" style={{ width: '60px', align: 'center' }}>
                {text}ms
              </Tag>
            );
          } else if (textNum > 2000) {
            tag = (
              <Tag color="#ff4d4f" style={{ width: '60px', align: 'center' }}>
                {text}ms
              </Tag>
            );
          } else {
            tag = (
              <Tag color="#009688" style={{ width: '60px', align: 'center' }}>
                0ms
              </Tag>
            );
          }
        } else {
          tag = (
            <Tag color="#009688" style={{ width: '60px', align: 'center' }}>
              {text}ms
            </Tag>
          );
        }
        return tag;
      },
    },
    {
      title: '执行时间',
      key: 'createtime',
      dataIndex: 'createtime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      width: 100,
      render: (text, record) => {
        return (
          <>
            <Popconfirm title="确认删除吗?" onConfirm={() => handleDel(record)}>
              <Button type="primary" size="small" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey={(record) => record.id}
        request={(params, sorter, filter, type = '0') =>
          queryAppJobLogList({ ...params, sorter, filter, type })
        }
        columns={columns}
        search={{
          collapsed: false,
          collapseRender: () => false,
        }}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Button
            type="primary"
            danger
            onClick={async () => {
              await handleDelBatch(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
